package com.company.test29;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by v on 16-11-28.
 */
public class TestSynchronized {
    private static Account account1=new Account();
    private static Account account2=new Account();
    private static HashMap map=new HashMap();

    private static class addAccount implements Runnable{
        @Override
        public void run() {
            for(int i=0;i<100;i++){
                synchronized (account1){
                    account1.addAccount();
                }
                System.out.println(account1.getAccount());
            }
        }
    }

    private static class ChangeAccount1 implements Runnable{
        @Override
        public void run() {
            synchronized (account1){
                try {
                    int a1=account1.getAccount();
                    Thread.sleep(5);
                    synchronized (account2){
                        int a2=account2.getAccount();
                        account1.account=a2+10;
                        System.out.println("a1 to a2");
                    }
                }catch (InterruptedException ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    private static class ChangeAccount2 implements Runnable{
        @Override
        public void run() {
            synchronized (account2){
                try {
                    int a2=account2.getAccount();
                    Thread.sleep(5);
                    synchronized (account1){
                        account1.account=a2+10;
                        System.out.println("a2 to a1");
                    }
                }catch (InterruptedException ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    private static class Account{
        private static int account;
        public Account(){
            account=0;
        }

        public void addAccount(){
            try {
                int temp=account+1;

                Thread.sleep(5);

                account=temp;
            }catch (InterruptedException ex){
                ex.printStackTrace();
            }
        }

        public int getAccount(){
            return account;
        }
    }

    public static void main(String[] args) {
        long time=System.currentTimeMillis();

        ChangeAccount1 a1=new ChangeAccount1();
        ChangeAccount2 a2=new ChangeAccount2();
        ExecutorService executor=Executors.newCachedThreadPool();

        executor.execute(a1);
        executor.execute(a2);

        executor.shutdown();


    }
}